#!/usr/bin/python2

import argparse
import itertools
import os
import time

import cv2
import numpy
import openface

import get_features

start = time.time()
numpy.set_printoptions(precision=2)
align = openface.AlignDlib("shape_predictor_68_face_landmarks.dat")

def get_faces(imgPath):
    print("Processing {}.".format(imgPath))
    bgr_img = cv2.imread(imgPath)
    if bgr_img is None:
        raise Exception("Unable to load image: {}".format(imgPath))
    rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)

    print("  + Original size: {}".format(rgb_img.shape))

    start = time.time()
    bb = align.getAllFaceBoundingBoxes(rgb_img)

    for iter, img in enumerate(bb):
        x1 = abs(img.tl_corner().x)
        y1 = abs(img.tl_corner().y)
        x2 = abs(img.br_corner().x)
        y2 = abs(img.br_corner().y)
        print(x1, x2, y1, y2)
        crop_img = bgr_img[y1:y2, x1:x2]
        cv2.imwrite("face{}.png".format(iter), crop_img)
        get_features.get_features(rgb_img, img)

parser = argparse.ArgumentParser()
parser.add_argument('img', type=str, help="Input image.")
args = parser.parse_args()
get_faces(args.img)